/**
 * Created by LaoXu on 2017/12/20.
 * @description:菜品页面功能实现
 */
/*<li>
 <img src="images/meishi-img.png"/>
 <div class="fontSmalSize">
 <h3>剁椒鱼头</h3>
 <p>¥110</p>
 </div>
 <div>
 <button>已添加</button>
 </div>
 </li>*/
require(['config'], function () {
    require(['jquery', 'xutil'], function ($, xutil) {
        // 获取DOM节点
        var $foodsWrap = $('.foods-wrap');
        var $foodUl = $('.foods-wrap').children('ul');
        var $totalPrice = $('#totalPrice');
        var $totalNum = $('#totalNum');
        var $foodCommit = $('#food-commit');
        var localStorage = window.localStorage;

        // 获取本地存储的值
        var foodData = JSON.parse(localStorage.getItem('foodData')) || {};
        foodData['foodItem'] = foodData['foodItem'] || [];
        var selectItem = foodData['foodItem'];
        var currentData = [];// 存储所有商品数据


        var food = {
            init(){
                this.getFoodData();
                this.bindEvent();
                this.getTotle();
            },
            // 获取商品信息
            getFoodData(){
                // 获取url上的参数信息
                var that = this;
                var urlParams = xutil.getUrlParams(window.location.href);
                $.get(xutil.baseUrl + '/api/food/getDataList?shop_id=' + urlParams.shop_id, function (data) {
                    var str = '';

                    if (data.code === 0) {
                        currentData = data.datas;
                        // 找出返回当前数据与库中的数据是否对应，对应则表示已添加
                        currentData.forEach(function (item, index) {
                            var selected = false;
                            selectItem.forEach(function (selectItem, selectIndex) {
                                if (selectItem.food_id === item.food_id) {
                                    selected = true;
                                }
                            });

                            // 添加对应的节点
                            str += `<li>
                                        <img src="${item.img_url}"/>
                                        <div class="fontSmalSize">
                                            <h3>${item.food_name}</h3>
                                            <p>¥${item.price}</p>
                                        </div>
                                        <div>
                                            <button data-index="${index}" id="food_add" class="${selected ? 'added' : '' }"> ${selected ? '已添加' : '添加'}</button>
                                        </div>
                                    </li>`;
                        });

                        $foodUl.append(str);

                        that.getTotle();
                    } else {
                        console.log(data.code)
                    }
                });
            },
            // 绑定事件
            bindEvent(){
                var that = this;
                $foodUl.on('click', '#food_add', function () {
                    var $addBtn = $(this);
                    var index = $addBtn.attr('data-index');
                    if ($addBtn.hasClass('added')) { // 取消添加
                        $addBtn.removeClass('added').html('添加');

                        var currentId = currentData[index].food_id;
                        for (var i = 0; i < selectItem.length; i++) {
                            if (selectItem[i]['food_id']) {
                                if (selectItem[i].food_id === currentId) {
                                    // 如果在存储的数据中找到则移除它
                                    selectItem.splice(i, 1);
                                }
                            }

                        }

                    } else {// 点击添加
                        $addBtn.addClass('added').html('已添加');
                        selectItem.push(currentData[index]);
                    }

                    // 将数据存储至库中
                    localStorage.setItem('foodData', JSON.stringify(foodData));
                    that.getTotle();
                });
            },
            // 获取总数量及总价
            getTotle(){
                var totalNum = 0,
                    totalPrice = 0;
                // 获取被选中的总数以及它的总价
                selectItem.forEach(item => {
                    totalNum++;
                    totalPrice += parseInt(item.price);
                });
                // 设置总数及总价
                $totalPrice.html(totalPrice);
                $totalNum.html(totalNum);
            }
        }

        food.init();

        // 点击提交按钮
        $foodCommit.on('click', function () {
            window.location.href = './reg.html';
        });

    });
});

